import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 如果请求的地址不是login的话,则需要在请求头里增加token验证
    if (!config.url.includes('/sys/login')) {
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // 由于axios外层有一层data包住,所以要解构出来
    const { data: res } = response
    // 如果响应返回的是成功,则提示成功的message
    if (!res.success) {
      //如果响应返回的是失败,则提示失败的message
      Message.error(res.message)
      // 并且抛出一个错误
      throw new Error(res.message)
    }
    // 返回正常数据
    return res
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
